package com.socialcoco.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.socialcoco.entity.EpidemicSituation;
import com.socialcoco.entity.Grade;
import com.socialcoco.exception.myExection;
import com.socialcoco.respone.BaseResponse;
import com.socialcoco.respone.ResultUtils;
import com.socialcoco.respone.resultenum;
import com.socialcoco.serviceImpl.EpidemicSituationServiceImpl;
import com.socialcoco.serviceImpl.GradeServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  用户关于疫情的操作
 * </p>
 *
 * @author 赵志浩
 * @since 2022-04-18 08:57:22
 */
@Slf4j
@RestController
@RequestMapping("/socialcoco/user")
public class EpidemicSituationController {
    /**
     * 打卡后获得积分可以抽奖
     */
    @Autowired
    private EpidemicSituationServiceImpl epidemicSituationService;
    @Autowired
    private GradeServiceImpl gradeService;


    @ApiOperation("用户打卡疫情信息")
    @PostMapping("/signEpidemic")
    public BaseResponse<Object> signEpidemic(@RequestBody EpidemicSituation epidemicSituation, @RequestHeader("token") String token){
        if(epidemicSituation==null){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        epidemicSituation.setCreateTime(new Date());
        epidemicSituationService.save(epidemicSituation);
        QueryWrapper<Grade> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",epidemicSituation.getEuid());
        Grade one = gradeService.getOne(queryWrapper);
        log.info("dy"+one.toString());
        if(one==null){
            Grade grade=new Grade();
            grade.setFraction(10);
            grade.setUid(epidemicSituation.getEuid());
            gradeService.save(grade);
        }
        else{
            one.setFraction(one.getFraction()+10);
            gradeService.updateById(one);
        }
        return ResultUtils.success("saveOk");
    }
    @ApiOperation("判断用户今天是否打卡")
    @GetMapping("/isSignEpidemic/{euid}")
    public BaseResponse<Object> isSignEpidemic(@RequestHeader("token") String token, @PathVariable String euid){
        if(euid==null){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        QueryWrapper<EpidemicSituation> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("euid",euid).last("and date_format(createTime,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')");
        long count = epidemicSituationService.count(queryWrapper);
        if(count==0){
            return ResultUtils.success("canSign");
        }
        return ResultUtils.success("exist");
    }
}

